/////////////////////////////////////////////////////////////
document.addEventListener('DOMContentLoaded', function() {
    // 创建遮罩层
    const overlay = document.createElement('div');
    overlay.id = 'overlay';
    overlay.style.position = 'fixed';
    overlay.style.top = '0';
    overlay.style.left = '0';
    overlay.style.width = '100%';
    overlay.style.height = '100%';
    overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
    overlay.style.zIndex = '1000';
    overlay.style.display = 'flex';
    overlay.style.justifyContent = 'center';
    overlay.style.alignItems = 'center';

    // 创建提示框
    const popup = document.createElement('div');
    popup.id = 'popup';
    popup.style.backgroundColor = 'white';
    popup.style.padding = '30px';
    popup.style.borderRadius = '15px';
    popup.style.textAlign = 'center';
    popup.style.maxWidth = '600px';
    popup.style.boxShadow = '0 5px 15px rgba(0, 0, 0, 0.3)';

    // 提示框内容
    const popupContent = document.createElement('div');
    popupContent.style.marginBottom = '30px';
    popupContent.textContent = '请选择：';
    popupContent.style.fontSize = '24px';
    popupContent.style.fontWeight = 'bold';
    popupContent.style.color = '#333';

    // 创建选项按钮
    const options = ['我喜欢作者', '我不喜欢作者', '我很喜欢作者'];
    const buttonsContainer = document.createElement('div');
    buttonsContainer.style.display = 'flex';
    buttonsContainer.style.justifyContent = 'center';
    buttonsContainer.style.gap = '20px';
    buttonsContainer.style.flexWrap = 'wrap';

    options.forEach(option => {
        const button = document.createElement('button');
        button.textContent = option;
        button.style.padding = '15px 25px';
        button.style.borderRadius = '8px';
        button.style.backgroundColor = '#4CAF50';
        button.style.color = 'white';
        button.style.border = 'none';
        button.style.cursor = 'pointer';
        button.style.fontSize = '18px';
        button.style.transition = 'background-color 0.3s';
        button.style.boxShadow = '0 2px 5px rgba(0, 0, 0, 0.2)';
        button.style.minWidth = '200px';

        button.addEventListener('click', function() {
            if (option === '我不喜欢作者') {
                // 如果点击了“我不喜欢作者”，移除该按钮并允许点击其他按钮
                this.style.display = 'none';

                // 创建两张图片并贴在页面左右两边
                const imgLeft = document.createElement('img');
                imgLeft.src = 'https://tse1-mm.cn.bing.net/th/id/OIP-C.qUO_2EHK_FkNSYCBF16ESAHaHJ?w=216&h=208&c=7&r=0&o=7&pid=1.7&rm=3';
                imgLeft.style.position = 'fixed';
                imgLeft.style.left = '0';
                imgLeft.style.top = '50%';
                imgLeft.style.transform = 'translateY(-50%)';
                imgLeft.style.width = '300px'; // 增大图片宽度
                imgLeft.style.height = '300px'; // 增大图片高度
                imgLeft.style.objectFit = 'cover';
                imgLeft.style.zIndex = '1000'; // 与遮罩层相同层级

                const imgRight = document.createElement('img');
                imgRight.src = 'https://tse1-mm.cn.bing.net/th/id/OIP-C.qUO_2EHK_FkNSYCBF16ESAHaHJ?w=216&h=208&c=7&r=0&o=7&pid=1.7&rm=3';
                imgRight.style.position = 'fixed';
                imgRight.style.right = '0';
                imgRight.style.top = '50%';
                imgRight.style.transform = 'translateY(-50%)';
                imgRight.style.width = '300px'; // 增大图片宽度
                imgRight.style.height = '300px'; // 增大图片高度
                imgRight.style.objectFit = 'cover';
                imgRight.style.zIndex = '1000'; // 与遮罩层相同层级

                document.body.appendChild(imgLeft);
                document.body.appendChild(imgRight);

                // 存储图片元素以便后面移除
                this.imgLeft = imgLeft;
                this.imgRight = imgRight;
            } else {
                // 创建两张图片并贴在页面左右两边
                const imgLeft = document.createElement('img');
                imgLeft.src = 'https://tse4-mm.cn.bing.net/th/id/OIP-C.pGQWpqGG-i2jJbYQPtPmwAAAAA?w=205&h=210&c=7&r=0&o=7&pid=1.7&rm=3';
                imgLeft.style.position = 'fixed';
                imgLeft.style.left = '0';
                imgLeft.style.top = '50%';
                imgLeft.style.transform = 'translateY(-50%)';
                imgLeft.style.width = '300px'; // 增大图片宽度
                imgLeft.style.height = '300px'; // 增大图片高度
                imgLeft.style.objectFit = 'cover';
                imgLeft.style.zIndex = '1000'; // 与遮罩层相同层级

                const imgRight = document.createElement('img');
                imgRight.src = 'https://tse4-mm.cn.bing.net/th/id/OIP-C.pGQWpqGG-i2jJbYQPtPmwAAAAA?w=205&h=210&c=7&r=0&o=7&pid=1.7&rm=3';
                imgRight.style.position = 'fixed';
                imgRight.style.right = '0';
                imgRight.style.top = '50%';
                imgRight.style.transform = 'translateY(-50%)';
                imgRight.style.width = '300px'; // 增大图片宽度
                imgRight.style.height = '300px'; // 增大图片高度
                imgRight.style.objectFit = 'cover';
                imgRight.style.zIndex = '1000'; // 与遮罩层相同层级

                document.body.appendChild(imgLeft);
                document.body.appendChild(imgRight);

                // 显示提示信息并隐藏遮罩层
                alert('好诶！');
                document.body.removeChild(overlay);
            }
        });

        buttonsContainer.appendChild(button);
    });

    // 将内容添加到提示框
    popup.appendChild(popupContent);
    popup.appendChild(buttonsContainer);

    // 将提示框添加到遮罩层
    overlay.appendChild(popup);

    // 将遮罩层添加到页面
    document.body.appendChild(overlay);

    // 防止用户在选择之前对页面的其他部分进行操作
    document.body.style.overflow = 'hidden';

    // 添加点击遮罩层关闭提示框的功能（可选）
    overlay.addEventListener('click', function(event) {
        if (event.target === overlay) {
            document.body.removeChild(overlay);
            document.body.style.overflow = 'auto';
        }
    });

    // 添加点击“我不喜欢作者”按钮后移除图片的功能
    buttonsContainer.addEventListener('click', function(event) {
        if (event.target.textContent === '我不喜欢作者' && event.target.style.display !== 'none') {
            // 在遮罩层消失时移除图片
            overlay.addEventListener('click', function() {
                if (event.target.imgLeft && event.target.imgRight) {
                    document.body.removeChild(event.target.imgLeft);
                    document.body.removeChild(event.target.imgRight);
                }
                document.body.style.overflow = 'auto';
            });
        }
    });
});

///////////////////////////////////////////
// 添加神秘按钮点击事件
document.getElementById('mystery-button').addEventListener('click', startGame);

// 游戏变量
let gameRunning = false;
let score = 0;
let lives = 3;
let gameInterval;
let enemies = [];
let bullets = [];
let player = {
    x: 400,
    y: 550,
    width: 50,
    height: 50,
    speed: 8 // 提高玩家速度
};
let canvas; // 定义 canvas
let canvasContext; // 定义 canvasContext

// 初始化游戏
function initGame() {
    // 获取 canvas 和 context
    canvas = document.getElementById('game-canvas');
    canvasContext = canvas.getContext('2d');

    document.getElementById('score').textContent = '0';
    document.getElementById('lives').textContent = '3';
    score = 0;
    lives = 3;
    enemies = [];
    bullets = [];
    player.x = canvas.width / 2 - player.width / 2;
    player.y = canvas.height - player.height - 10;
    gameRunning = true;
}

// 游戏循环
function gameLoop() {
    if (!gameRunning) return;

    canvasContext.clearRect(0, 0, canvas.width, canvas.height);

    // 绘制玩家
    drawPlayer();

    // 随机生成敌人
    if (Math.random() < 0.02) {
        createEnemy();
    }

    // 更新和绘制敌人
    updateEnemies();

    // 更新和绘制子弹
    updateBullets();

    // 检测碰撞
    checkCollisions();

    // 继续游戏循环
    gameInterval = requestAnimationFrame(gameLoop);
}

// 绘制玩家
function drawPlayer() {
    canvasContext.fillStyle = '#3498db';
    canvasContext.beginPath();
    canvasContext.moveTo(player.x + player.width / 2, player.y);
    canvasContext.lineTo(player.x + player.width, player.y + player.height);
    canvasContext.lineTo(player.x, player.y + player.height);
    canvasContext.closePath();
    canvasContext.fill();
}

// 创建敌人
function createEnemy() {
    const size = Math.random() * 30 + 20;
    const enemy = {
        x: Math.random() * (canvas.width - size),
        y: -size,
        width: size,
        height: size,
        speed: Math.random() * 1.5 + 0.5 // 降低敌人速度
    };
    enemies.push(enemy);
}

// 更新敌人位置
function updateEnemies() {
    for (let i = 0; i < enemies.length; i++) {
        const enemy = enemies[i];
        enemy.y += enemy.speed;

        // 绘制敌人
        canvasContext.fillStyle = '#e74c3c';
        canvasContext.beginPath();
        canvasContext.arc(enemy.x + enemy.width / 2, enemy.y + enemy.height / 2, enemy.width / 2, 0, Math.PI * 2);
        canvasContext.fill();

        // 移除超出屏幕的敌人
        if (enemy.y > canvas.height) {
            enemies.splice(i, 1);
            i--;
        }
    }
}

// 发射子弹
function shootBullet() {
    if (!gameRunning) return;

    const bullet = {
        x: player.x + player.width / 2 - 2,
        y: player.y,
        width: 4,
        height: 10,
        speed: 7
    };
    bullets.push(bullet);
}

// 更新子弹位置
function updateBullets() {
    for (let i = 0; i < bullets.length; i++) {
        const bullet = bullets[i];
        bullet.y -= bullet.speed;

        // 绘制子弹
        canvasContext.fillStyle = '#2ecc71';
        canvasContext.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);

        // 移除超出屏幕的子弹
        if (bullet.y < 0) {
            bullets.splice(i, 1);
            i--;
        }
    }
}

// 检测碰撞
function checkCollisions() {
    // 子弹与敌人碰撞
    for (let i = 0; i < bullets.length; i++) {
        for (let j = 0; j < enemies.length; j++) {
            if (isColliding(bullets[i], enemies[j])) {
                bullets.splice(i, 1);
                enemies.splice(j, 1);
                i--;
                j--;
                score += 10;
                document.getElementById('score').textContent = score;
                break;
            }
        }
    }

    // 玩家与敌人碰撞
    for (let i = 0; i < enemies.length; i++) {
        if (isColliding(player, enemies[i])) {
            enemies.splice(i, 1);
            i--;
            lives--;
            document.getElementById('lives').textContent = lives;

            if (lives <= 0) {
                gameOver();
            }
        }
    }
}

// 碰撞检测函数
function isColliding(obj1, obj2) {
    return obj1.x < obj2.x + obj2.width &&
        obj1.x + obj1.width > obj2.x &&
        obj1.y < obj2.y + obj2.height &&
        obj1.y + obj1.height > obj2.y;
}

// 游戏结束
function gameOver() {
    gameRunning = false;
    cancelAnimationFrame(gameInterval);
    document.getElementById('final-score').textContent = score;
    document.getElementById('game-over').style.display = 'block';
}

// 重新开始游戏
document.getElementById('restart-button').addEventListener('click', function() {
    document.getElementById('game-over').style.display = 'none';
    initGame();
    gameLoop();
});

// 键盘控制
document.addEventListener('keydown', function(event) {
    if (event.key === 'ArrowLeft') {
        player.x = Math.max(0, player.x - player.speed);
    } else if (event.key === 'ArrowRight') {
        player.x = Math.min(canvas.width - player.width, player.x + player.speed);
    } else if (event.key === ' ' || event.key === 'Spacebar') { // 用空格键发射子弹
        shootBullet();
    }
});

// 开始游戏
function startGame() {
    const gameContainer = document.getElementById('game-container');
    gameContainer.style.display = 'block';
    initGame();
    gameLoop();

    // 关闭游戏的ESC键
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            gameContainer.style.display = 'none';
            if (gameRunning) {
                gameOver();
            }
        }
    });
}
/////////////////////////////////////////////////////////////
document.addEventListener('DOMContentLoaded', function() {
    // 创建遮罩层
    const overlay = document.createElement('div');
    overlay.id = 'overlay';
    overlay.style.position = 'fixed';
    overlay.style.top = '0';
    overlay.style.left = '0';
    overlay.style.width = '100%';
    overlay.style.height = '100%';
    overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
    overlay.style.zIndex = '1000';
    overlay.style.display = 'flex';
    overlay.style.justifyContent = 'center';
    overlay.style.alignItems = 'center';

    // 创建提示框
    const popup = document.createElement('div');
    popup.id = 'popup';
    popup.style.backgroundColor = 'white';
    popup.style.padding = '30px';
    popup.style.borderRadius = '15px';
    popup.style.textAlign = 'center';
    popup.style.maxWidth = '600px';
    popup.style.boxShadow = '0 5px 15px rgba(0, 0, 0, 0.3)';

    // 提示框内容
    const popupContent = document.createElement('div');
    popupContent.style.marginBottom = '30px';
    popupContent.textContent = '请选择：';
    popupContent.style.fontSize = '24px';
    popupContent.style.fontWeight = 'bold';
    popupContent.style.color = '#333';

    // 创建选项按钮
    const options = ['我喜欢作者', '我不喜欢作者', '我很喜欢作者'];
    const buttonsContainer = document.createElement('div');
    buttonsContainer.style.display = 'flex';
    buttonsContainer.style.justifyContent = 'center';
    buttonsContainer.style.gap = '20px';
    buttonsContainer.style.flexWrap = 'wrap';

    options.forEach(option => {
        const button = document.createElement('button');
        button.textContent = option;
        button.style.padding = '15px 25px';
        button.style.borderRadius = '8px';
        button.style.backgroundColor = '#4CAF50';
        button.style.color = 'white';
        button.style.border = 'none';
        button.style.cursor = 'pointer';
        button.style.fontSize = '18px';
        button.style.transition = 'background-color 0.3s';
        button.style.boxShadow = '0 2px 5px rgba(0, 0, 0, 0.2)';
        button.style.minWidth = '200px';

        button.addEventListener('click', function() {
            if (option === '我不喜欢作者') {
                // 如果点击了“我不喜欢作者”，移除该按钮并允许点击其他按钮
                this.style.display = 'none';

                // 创建两张图片并贴在页面左右两边
                const imgLeft = document.createElement('img');
                imgLeft.src = 'https://tse1-mm.cn.bing.net/th/id/OIP-C.qUO_2EHK_FkNSYCBF16ESAHaHJ?w=216&h=208&c=7&r=0&o=7&pid=1.7&rm=3';
                imgLeft.style.position = 'fixed';
                imgLeft.style.left = '0';
                imgLeft.style.top = '50%';
                imgLeft.style.transform = 'translateY(-50%)';
                imgLeft.style.width = '300px'; // 增大图片宽度
                imgLeft.style.height = '300px'; // 增大图片高度
                imgLeft.style.objectFit = 'cover';
                imgLeft.style.zIndex = '1000'; // 与遮罩层相同层级

                const imgRight = document.createElement('img');
                imgRight.src = 'https://tse1-mm.cn.bing.net/th/id/OIP-C.qUO_2EHK_FkNSYCBF16ESAHaHJ?w=216&h=208&c=7&r=0&o=7&pid=1.7&rm=3';
                imgRight.style.position = 'fixed';
                imgRight.style.right = '0';
                imgRight.style.top = '50%';
                imgRight.style.transform = 'translateY(-50%)';
                imgRight.style.width = '300px'; // 增大图片宽度
                imgRight.style.height = '300px'; // 增大图片高度
                imgRight.style.objectFit = 'cover';
                imgRight.style.zIndex = '1000'; // 与遮罩层相同层级

                document.body.appendChild(imgLeft);
                document.body.appendChild(imgRight);

                // 存储图片元素以便后面移除
                this.imgLeft = imgLeft;
                this.imgRight = imgRight;
            } else {
                // 创建两张图片并贴在页面左右两边
                const imgLeft = document.createElement('img');
                imgLeft.src = 'https://tse4-mm.cn.bing.net/th/id/OIP-C.pGQWpqGG-i2jJbYQPtPmwAAAAA?w=205&h=210&c=7&r=0&o=7&pid=1.7&rm=3';
                imgLeft.style.position = 'fixed';
                imgLeft.style.left = '0';
                imgLeft.style.top = '50%';
                imgLeft.style.transform = 'translateY(-50%)';
                imgLeft.style.width = '300px'; // 增大图片宽度
                imgLeft.style.height = '300px'; // 增大图片高度
                imgLeft.style.objectFit = 'cover';
                imgLeft.style.zIndex = '1000'; // 与遮罩层相同层级

                const imgRight = document.createElement('img');
                imgRight.src = 'https://tse4-mm.cn.bing.net/th/id/OIP-C.pGQWpqGG-i2jJbYQPtPmwAAAAA?w=205&h=210&c=7&r=0&o=7&pid=1.7&rm=3';
                imgRight.style.position = 'fixed';
                imgRight.style.right = '0';
                imgRight.style.top = '50%';
                imgRight.style.transform = 'translateY(-50%)';
                imgRight.style.width = '300px'; // 增大图片宽度
                imgRight.style.height = '300px'; // 增大图片高度
                imgRight.style.objectFit = 'cover';
                imgRight.style.zIndex = '1000'; // 与遮罩层相同层级

                document.body.appendChild(imgLeft);
                document.body.appendChild(imgRight);

                // 显示提示信息并隐藏遮罩层
                alert('好诶！');
                document.body.removeChild(overlay);
            }
        });

        buttonsContainer.appendChild(button);
    });

    // 将内容添加到提示框
    popup.appendChild(popupContent);
    popup.appendChild(buttonsContainer);

    // 将提示框添加到遮罩层
    overlay.appendChild(popup);

    // 将遮罩层添加到页面
    document.body.appendChild(overlay);

    // 防止用户在选择之前对页面的其他部分进行操作
    document.body.style.overflow = 'hidden';

    // 添加点击遮罩层关闭提示框的功能（可选）
    overlay.addEventListener('click', function(event) {
        if (event.target === overlay) {
            document.body.removeChild(overlay);
            document.body.style.overflow = 'auto';
        }
    });

    // 添加点击“我不喜欢作者”按钮后移除图片的功能
    buttonsContainer.addEventListener('click', function(event) {
        if (event.target.textContent === '我不喜欢作者' && event.target.style.display !== 'none') {
            // 在遮罩层消失时移除图片
            overlay.addEventListener('click', function() {
                if (event.target.imgLeft && event.target.imgRight) {
                    document.body.removeChild(event.target.imgLeft);
                    document.body.removeChild(event.target.imgRight);
                }
                document.body.style.overflow = 'auto';
            });
        }
    });
});

document.addEventListener('DOMContentLoaded', function() {
    const loginPage = document.getElementById('login-page');
    const registerPage = document.getElementById('register-page');
    const merchantPage = document.getElementById('merchant-page');
    const userPage = document.getElementById('user-page');
    const adminPage = document.getElementById('admin-page');
    const allProductsPage = document.getElementById('all-products-page');

    let currentUser = null;
    let currentMerchant = null;
    let currentAdmin = null;

    // 登录按钮点击事件
    document.getElementById('login-button').addEventListener('click', function() {
        const id = parseInt(document.getElementById('login-id').value);
        const password = document.getElementById('login-password').value;
        const type = document.getElementById('login-type').value;

        let requestPayload;
        if (type === 'admin') {
            requestPayload = { adminId: id, password: password };
        } else if (type === 'merchant') {
            requestPayload = { merchantId: id, password: password };
        } else if (type === 'user') {
            requestPayload = { userId: id, password: password };
        }

        axios.post(`http://localhost:8080/${type}/login`, requestPayload)
            .then(response => {
                if (response.data) {
                    if (type === 'admin') {
                        currentAdmin = response.data;
                        adminPage.classList.remove('hidden');
                        loginPage.classList.add('hidden');
                        updateWelcomeMessage('admin', currentAdmin.nickname);
                        loadAdminData();
                        setupAdminEventListeners(); // 在这里调用
                    } else if (type === 'merchant') {
                        currentMerchant = response.data;
                        merchantPage.classList.remove('hidden');
                        loginPage.classList.add('hidden');
                        updateWelcomeMessage('merchant', currentMerchant.nickname);
                        loadMerchantData();
                    } else if (type === 'user') {
                        currentUser = response.data;
                        userPage.classList.remove('hidden');
                        loginPage.classList.add('hidden');
                        updateWelcomeMessage('user', currentUser.nickname);
                        loadUserData();
                    }
                } else {
                    document.getElementById('login-error').textContent = '账号或密码错误';
                }
            })
            .catch(error => {
                document.getElementById('login-error').textContent = '登录失败';
                console.error('登录失败:', error);
            });
    });

    // 管理员查询用户按钮点击事件
    document.getElementById('query-users').addEventListener('click', function() {
        const usersContainer = document.getElementById('admin-users');
        if (usersContainer.classList.contains('hidden')) {
            axios.get('http://localhost:8080/admin/users')
                .then(response => {
                    usersContainer.innerHTML = '';
                    response.data.forEach(user => {
                        const userElement = document.createElement('div');
                        userElement.className = 'user-item';
                        userElement.innerHTML = `
                            <p>ID: ${user.userId}</p>
                            <p>昵称: ${user.nickname}</p>
                        `;
                        usersContainer.appendChild(userElement);
                    });
                    usersContainer.classList.remove('hidden');
                })
                .catch(error => {
                    console.error('加载用户列表失败', error);
                });
        } else {
            usersContainer.classList.add('hidden');
        }
    });

    // 管理员查询商家按钮点击事件
    document.getElementById('query-merchants').addEventListener('click', function() {
        const merchantsContainer = document.getElementById('admin-merchants');
        if (merchantsContainer.classList.contains('hidden')) {
            axios.get('http://localhost:8080/admin/merchants')
                .then(response => {
                    merchantsContainer.innerHTML = '';
                    response.data.forEach(merchant => {
                        const merchantElement = document.createElement('div');
                        merchantElement.className = 'merchant-item';
                        merchantElement.innerHTML = `
                            <p>ID: ${merchant.merchantId}</p>
                            <p>昵称: ${merchant.nickname}</p>
                        `;
                        merchantsContainer.appendChild(merchantElement);
                    });
                    merchantsContainer.classList.remove('hidden');
                })
                .catch(error => {
                    console.error('加载商家列表失败', error);
                });
        } else {
            merchantsContainer.classList.add('hidden');
        }
    });

    // 注册页面事件
    document.getElementById('go-to-register').addEventListener('click', function(e) {
        e.preventDefault(); // 防止默认行为（刷新页面）
        registerPage.classList.remove('hidden');
        loginPage.classList.add('hidden');
    });
    document.getElementById('register-button').addEventListener('click', function() {
        const type = document.getElementById('register-type').value;
        const nickname = document.getElementById('register-nickname').value;
        const password = document.getElementById('register-password').value;

        axios.post(`http://localhost:8080/${type}/register`, {
            nickname: nickname,
            password: password
        })
            .then(response => {
                if (response.data.success) {
                    alert(`注册成功！您的ID是：${response.data.id}`);
                    registerPage.classList.add('hidden');
                    loginPage.classList.remove('hidden');
                    document.getElementById('register-error').textContent = '';
                } else {
                    document.getElementById('register-error').textContent = response.data.message || '注册失败';
                }
            })
            .catch(error => {
                if (error.response && error.response.data) {
                    document.getElementById('register-error').textContent = error.response.data.message || '注册失败';
                } else {
                    document.getElementById('register-error').textContent = '注册失败：网络错误或服务不可用';
                }
                console.error('注册失败:', error);
            });
    });

    document.getElementById('go-to-login').addEventListener('click', function(e) {
        e.preventDefault();
        loginPage.classList.remove('hidden');
        registerPage.classList.add('hidden');
    });

    // 商家页面事件
    document.getElementById('merchant-logout').addEventListener('click', function() {
        merchantPage.classList.add('hidden');
        loginPage.classList.remove('hidden');
        currentMerchant = null;
        removeWelcomeMessage('merchant');
    });

    document.getElementById('add-product').addEventListener('click', function() {
        const name = document.getElementById('product-name').value;
        const description = document.getElementById('product-description').value;
        const price = parseFloat(document.getElementById('product-price').value);

        const product = {
            name: name,
            description: description,
            price: price,
            merchantId: currentMerchant.merchantId
        };

        axios.post('http://localhost:8080/product', product)
            .then(response => {
                if (response.data === 'Product added successfully') {
                    loadMerchantData();
                }
            })
            .catch(error => {
                console.error('添加商品失败', error);
            });
    });

    document.getElementById('update-profile').addEventListener('click', function() {
        const newNickname = document.getElementById('new-nickname').value;
        const newPassword = document.getElementById('new-password').value;

        const updatedMerchant = {
            merchantId: currentMerchant.merchantId,
            newNickname: newNickname,
            newPassword: newPassword
        };

        axios.put('http://localhost:8080/merchant/profile', updatedMerchant)
            .then(response => {
                if (response.data === 'Profile updated successfully') {
                    currentMerchant.nickname = newNickname;
                    updateWelcomeMessage('merchant', newNickname);
                    loadMerchantData();
                }
            })
            .catch(error => {
                console.error('更新资料失败', error);
            });
    });

    // 用户页面事件
    document.getElementById('user-logout').addEventListener('click', function() {
        userPage.classList.add('hidden');
        loginPage.classList.remove('hidden');
        currentUser = null;
        removeWelcomeMessage('user');
    });

    document.getElementById('user-update-profile').addEventListener('click', function() {
        const newNickname = document.getElementById('user-new-nickname').value;
        const newPassword = document.getElementById('user-new-password').value;

        const updatedUser = {
            userId: currentUser.userId,
            newNickname: newNickname,
            newPassword: newPassword
        };

        axios.put('http://localhost:8080/user/profile', updatedUser)
            .then(response => {
                if (response.data === 'Profile updated successfully') {
                    currentUser.nickname = newNickname;
                    updateWelcomeMessage('user', newNickname);
                    loadUserData();
                }
            })
            .catch(error => {
                console.error('更新资料失败', error);
            });
    });

    // 用户查看全部商品按钮点击事件
    const viewAllButton = document.getElementById('view-all-products-button');
    if (viewAllButton) {
        viewAllButton.addEventListener('click', function() {
            // 隐藏用户页面，显示全部商品页面
            userPage.classList.add('hidden');
            allProductsPage.classList.remove('hidden');
            loadAllProducts();
        });
    }

    // 返回用户界面按钮点击事件
    const backButton = document.getElementById('back-to-user');
    if (backButton) {
        backButton.addEventListener('click', function() {
            // 隐藏全部商品页面，显示用户页面
            allProductsPage.classList.add('hidden');
            userPage.classList.remove('hidden');
        });
    }

    // 管理员页面事件
    function setupAdminEventListeners() {
        // 管理员退出登录事件
        const adminLogoutButton = document.getElementById('admin-logout');
        if (adminLogoutButton) {
            adminLogoutButton.addEventListener('click', function() {
                adminPage.classList.add('hidden');
                loginPage.classList.remove('hidden');
                currentAdmin = null;
                removeWelcomeMessage('admin');
            });
        }

        // 删除用户事件
        const deleteUserButton = document.getElementById('delete-user');
        if (deleteUserButton) {
            deleteUserButton.addEventListener('click', function() {
                const userId = parseInt(document.getElementById('delete-user-id').value);

                axios.delete(`http://localhost:8080/admin/users/${userId}`)
                    .then(response => {
                        if (response.data === 'User deleted successfully') {
                            loadAdminData();
                        }
                    })
                    .catch(error => {
                        console.error('删除用户失败', error);
                    });
            });
        }

        // 删除商家事件
        const deleteMerchantButton = document.getElementById('delete-merchant');
        if (deleteMerchantButton) {
            deleteMerchantButton.addEventListener('click', function() {
                const merchantId = parseInt(document.getElementById('delete-merchant-id').value);

                axios.delete(`http://localhost:8080/admin/merchants/${merchantId}`)
                    .then(response => {
                        if (response.data === 'Merchant deleted successfully') {
                            loadAdminData();
                        }
                    })
                    .catch(error => {
                        console.error('删除商家失败', error);
                    });
            });
        }
    }

    document.getElementById('update-admin-password').addEventListener('click', function() {
        const newPassword = document.getElementById('new-admin-password').value;

        const updatedAdmin = {
            adminId: currentAdmin.adminId,
            newPassword: newPassword
        };

        axios.put('http://localhost:8080/admin/password', updatedAdmin)
            .then(response => {
                if (response.data === 'Password updated successfully') {
                    alert('密码更新成功');
                }
            })
            .catch(error => {
                console.error('更新密码失败', error);
            });
    });

    // 加载商品数据
    function loadAllProducts() {
        axios.get('http://localhost:8080/product')
            .then(response => {
                const productsContainer = document.getElementById('all-products-list');
                productsContainer.innerHTML = '';
                response.data.forEach(product => {
                    axios.get(`http://localhost:8080/merchant/profile?merchantId=${product.merchantId}`)
                        .then(merchantResponse => {
                            const merchant = merchantResponse.data;
                            const productElement = document.createElement('div');
                            productElement.className = 'product-item';
                            productElement.innerHTML = `
                                <h4>${product.name}</h4>
                                <p>${product.description}</p>
                                <p>价格：¥${product.price}</p>
                                <p class="product-seller">卖家：${merchant.nickname}</p>
                                <button class="buy-button" data-product-id="${product.productId}">购买</button>
                            `;
                            productsContainer.appendChild(productElement);

                            document.querySelectorAll('.buy-button').forEach(button => {
                                button.addEventListener('click', function() {
                                    const productId = parseInt(this.getAttribute('data-product-id'));
                                    const productClicked = response.data.find(p => p.productId === productId);

                                    const overlay = document.createElement('div');
                                    overlay.id = 'buy-overlay';
                                    overlay.style.position = 'fixed';
                                    overlay.style.top = '0';
                                    overlay.style.left = '0';
                                    overlay.style.width = '100%';
                                    overlay.style.height = '100%';
                                    overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
                                    overlay.style.zIndex = '1000';
                                    overlay.style.display = 'flex';
                                    overlay.style.justifyContent = 'center';
                                    overlay.style.alignItems = 'center';

                                    const popup = document.createElement('div');
                                    popup.id = 'buy-popup';
                                    popup.style.backgroundColor = 'white';
                                    popup.style.padding = '30px';
                                    popup.style.borderRadius = '15px';
                                    popup.style.textAlign = 'center';
                                    popup.style.maxWidth = '400px';
                                    popup.style.boxShadow = '0 5px 15px rgba(0, 0, 0, 0.3)';

                                    const popupContent = document.createElement('div');
                                    popupContent.style.marginBottom = '30px';
                                    popupContent.innerHTML = `
            <h3>确认购买</h3>
            <p>商品：${productClicked.name}</p>
            <p>价格：¥${productClicked.price}</p>
            <p>卖家：${merchant.nickname}</p>
        `;

                                    // 确认购买按钮的逻辑
                                    const confirmButton = document.createElement('button');
                                    confirmButton.textContent = '确认购买';
                                    confirmButton.style.padding = '10px 20px';
                                    confirmButton.style.borderRadius = '5px';
                                    confirmButton.style.backgroundColor = '#4CAF50';
                                    confirmButton.style.color = 'white';
                                    confirmButton.style.border = 'none';
                                    confirmButton.style.cursor = 'pointer';

                                    confirmButton.addEventListener('click', function() {
                                        const purchaseRecord = {
                                            userId: currentUser.userId,
                                            merchantId: productClicked.merchantId,
                                            productId: productClicked.productId
                                        };

                                        axios.post('http://localhost:8080/purchase', purchaseRecord)
                                            .then(response => {
                                                return axios.delete(`http://localhost:8080/product/${productClicked.productId}`);
                                            })
                                            .then(response => {
                                                alert('购买成功，商品已下架！');
                                                document.body.removeChild(overlay); // 移除覆盖框
                                                loadAllProducts(); // 刷新页面数据
                                            })
                                            .catch(error => {
                                                console.error('购买失败', error);
                                            });
                                    });

                                    // 取消按钮的逻辑
                                    const cancelButton = document.createElement('button');
                                    cancelButton.textContent = '取消';
                                    cancelButton.style.padding = '10px 20px';
                                    cancelButton.style.borderRadius = '5px';
                                    cancelButton.style.backgroundColor = '#f44336';
                                    cancelButton.style.color = 'white';
                                    cancelButton.style.border = 'none';
                                    cancelButton.style.cursor = 'pointer';

                                    cancelButton.addEventListener('click', function() {
                                        document.body.removeChild(overlay); // 移除覆盖框
                                    });

                                    const buttonsContainer = document.createElement('div');
                                    buttonsContainer.style.display = 'flex';
                                    buttonsContainer.style.justifyContent = 'center';
                                    buttonsContainer.style.gap = '20px';

                                    buttonsContainer.appendChild(confirmButton);
                                    buttonsContainer.appendChild(cancelButton);

                                    popup.appendChild(popupContent);
                                    popup.appendChild(buttonsContainer);
                                    overlay.appendChild(popup);
                                    document.body.appendChild(overlay);
                                });
                            });
                        })
                        .catch(error => {
                            console.error('获取商家信息失败', error);
                        });
                });
            })
            .catch(error => {
                console.error('加载商品失败', error);
            });
    }

    function loadUserData() {
        axios.get(`http://localhost:8080/user/purchase-records?userId=${currentUser.userId}`)
            .then(response => {
                const historyContainer = document.getElementById('user-purchase-history');
                historyContainer.innerHTML = '';
                response.data.forEach(record => {
                    const recordElement = document.createElement('div');
                    recordElement.className = 'product-item';
                    recordElement.innerHTML = `
                        <p>商品ID：${record.productId}</p>
                        <p>商家ID：${record.merchantId}</p>
                        <p>购买时间：${record.purchaseTime}</p>
                    `;
                    historyContainer.appendChild(recordElement);
                });
            })
            .catch(error => {
                console.error('加载购买记录失败', error);
            });
    }

    function loadMerchantData() {
        axios.get(`http://localhost:8080/merchant/products?merchantId=${currentMerchant.merchantId}`)
            .then(response => {
                const productsContainer = document.getElementById('merchant-products');
                productsContainer.innerHTML = '';
                response.data.forEach(product => {
                    const productElement = document.createElement('div');
                    productElement.className = 'product-item';
                    productElement.innerHTML = `
                        <h4>${product.name}</h4>
                        <p>${product.description}</p>
                        <p>价格：¥${product.price}</p>
                        <button class="delete-product-button" data-product-id="${product.productId}">删除商品</button>
                    `;
                    productsContainer.appendChild(productElement);
                });

                document.querySelectorAll('.delete-product-button').forEach(button => {
                    button.addEventListener('click', function() {
                        const productId = parseInt(this.getAttribute('data-product-id'));
                        axios.delete(`http://localhost:8080/product/${productId}`)
                            .then(response => {
                                if (response.data === 'Product deleted successfully') {
                                    loadMerchantData();
                                }
                            })
                            .catch(error => {
                                console.error('删除商品失败', error);
                            });
                    });
                });
            })
            .catch(error => {
                console.error('加载商品失败', error);
            });

        // 加载商家的成交记录
        axios.get(`http://localhost:8080/merchant/purchase-records?merchantId=${currentMerchant.merchantId}`)
            .then(response => {
                const recordsContainer = document.getElementById('merchant-purchase-records');
                recordsContainer.innerHTML = '';
                response.data.forEach(record => {
                    const recordElement = document.createElement('div');
                    recordElement.className = 'product-item';
                    recordElement.innerHTML = `
                        <p>用户ID：${record.userId}</p>
                        <p>商品ID：${record.productId}</p>
                        <p>购买时间：${record.purchaseTime}</p>
                    `;
                    recordsContainer.appendChild(recordElement);
                });
            })
            .catch(error => {
                console.error('加载成交记录失败', error);
            });
    }

    function loadAdminData() {
        axios.get('http://localhost:8080/admin/users')
            .then(response => {
                const usersContainer = document.getElementById('admin-users');
                usersContainer.innerHTML = '';
                response.data.forEach(user => {
                    const userElement = document.createElement('div');
                    userElement.className = 'user-item';
                    userElement.innerHTML = `
                        <p>ID: ${user.userId}</p>
                        <p>昵称: ${user.nickname}</p>
                    `;
                    usersContainer.appendChild(userElement);
                });
            })
            .catch(error => {
                console.error('加载用户列表失败', error);
            });

        axios.get('http://localhost:8080/admin/merchants')
            .then(response => {
                const merchantsContainer = document.getElementById('admin-merchants');
                merchantsContainer.innerHTML = '';
                response.data.forEach(merchant => {
                    const merchantElement = document.createElement('div');
                    merchantElement.className = 'merchant-item';
                    merchantElement.innerHTML = `
                        <p>ID: ${merchant.merchantId}</p>
                        <p>昵称: ${merchant.nickname}</p>
                    `;
                    merchantsContainer.appendChild(merchantElement);
                });
            })
            .catch(error => {
                console.error('加载商家列表失败', error);
            });

        axios.get('http://localhost:8080/admin/counts')
            .then(response => {
                document.getElementById('user-count').textContent = `用户数量：${response.data.userCount}`;
                document.getElementById('merchant-count').textContent = `商家数量：${response.data.merchantCount}`;
            })
            .catch(error => {
                console.error('加载数量失败', error);
            });

        axios.get('http://localhost:8080/admin/purchase-records')
            .then(response => {
                const recordsContainer = document.getElementById('admin-purchase-records');
                recordsContainer.innerHTML = '';
                response.data.forEach(record => {
                    const recordElement = document.createElement('div');
                    recordElement.className = 'product-item';
                    recordElement.innerHTML = `
                        <p>用户ID：${record.userId}</p>
                        <p>商家ID：${record.merchantId}</p>
                        <p>购买时间：${record.purchaseTime}</p>
                    `;
                    recordsContainer.appendChild(recordElement);
                });
            })
            .catch(error => {
                console.error('加载成交记录失败', error);
            });
    }

    function updateWelcomeMessage(type, nickname) {
        const welcomeElement = document.getElementById(`${type}-welcome`);
        if (welcomeElement) {
            welcomeElement.textContent = `欢迎您，${nickname}！`;
        }
    }

    function removeWelcomeMessage(type) {
        const welcomeElement = document.getElementById(`${type}-welcome`);
        if (welcomeElement) {
            welcomeElement.textContent = '';
        }
    }

    // 初始化页面
    if (loginPage) loginPage.classList.remove('hidden');
    if (registerPage) registerPage.classList.add('hidden');
    if (merchantPage) merchantPage.classList.add('hidden');
    if (userPage) userPage.classList.add('hidden');
    if (adminPage) adminPage.classList.add('hidden');
    if (allProductsPage) allProductsPage.classList.add('hidden');
});